﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace JiaBoPrint
{
    internal class MultiComboBox : UserControl
    {
        private ComboBox comboBox = new ComboBox();
        public CheckedListBox CheckedListBox { get; set; }  //为选项赋值的接口
        public List<string> SelectedItems1 { get; set; }  //传递已选择项目的接口

        public MultiComboBox()
        {
            this.VerticalScroll.Enabled = true;
            this.AutoSize = true;
            CheckedListBox = new CheckedListBox();
            CheckedListBox.CheckOnClick = true;
            CheckedListBox.Visible = false;
            comboBox = new ComboBox();
            comboBox.Width = 150;
            comboBox.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox.IntegralHeight = false;
            comboBox.DroppedDown = false;
            comboBox.DropDownHeight = 1;
            comboBox.DropDownStyle = ComboBoxStyle.DropDown;
            comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
            CheckedListBox.MouseUp += MouseUp1;
            CheckedListBox.MouseLeave += MouseLeave1;
            comboBox.MouseDown += MouseDown1;
            comboBox.DropDown += MouseLeave2;
            this.Controls.Add(comboBox);   //添加控件
        }
        //
        #region 订阅方法模块
        //
        private void MouseLeave1(object sender, EventArgs e)  //鼠标离开CheckedListBox，隐藏CheckedListBox
        {
            CheckedListBox.Hide();
        }
        private void MouseLeave2(object sender, EventArgs e)  //ComboBox下拉时，显示下拉框
        {
            // 显示下拉框
            CheckedListBox.Width = comboBox.Width;
            CheckedListBox.Size = new Size(comboBox.DropDownWidth, CheckedListBox.Items.Count * 18);
            CheckedListBox.Location = new Point(comboBox.Left, comboBox.Height);
            Controls.Add(CheckedListBox);
            CheckedListBox.Visible = true;
        }
        private void MouseUp1(object sender, EventArgs e)  //在CheckedListBox中选择后，在ComboBox中显示相应项目
        {
            var list = new List<string>();
            foreach (var v in CheckedListBox.CheckedItems)  //将选择的项目加入list
            {
                list.Add(v.ToString());
            }
            comboBox.Text = String.Join(",", list);
            SelectedItems1 = list;  //把选项赋给传递接口
        }
        private void MouseDown1(object sender, EventArgs e) //在ComboBox的下拉三角按下鼠标时，不显示ComboBox的下拉框，显示CheckedListBox当作其下拉框
        {
            comboBox.DroppedDown = false;
        }
        #endregion 
        //
        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // MultiComboBox
            // 
            this.Name = "MultiComboBox";
            this.Size = new System.Drawing.Size(414, 84);
            this.ResumeLayout(false);

        }
    }

}
